<template>
  <div class="page-container page-container-detail-page">
    <!--面包屑导航-->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>营销中心</el-breadcrumb-item>
        <el-breadcrumb-item>通用促销</el-breadcrumb-item>
        <el-breadcrumb-item>秒杀详情</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="page-container-detail">
      <p class="pageName">秒杀详情</p>
      <div class="toolbar flex">
        <div class="toolbar-model">
          <span class="color333 font18">活动名称：</span>
          <span class="color333 font18">{{data.promName}}</span>
        </div>
        <div class="toolbar-model">
          <span class="color333 font18">活动ID：</span>
          <span class="color333 font18">{{data.promotionCode}}</span>
        </div>
        <div class="toolbar-model">
          <span class="color333 font18">当前状态：</span>
          <!--          活动状态 0初始化 1 待提交  2 待审核  3未开始 4 审核不通过  5 进行中  6 已过期  7 已关闭-->
          <span class="color333 font18"  v-if="data.status == 9">草稿状态</span>
          <span class="color333 font18"  v-else-if="data.status == 1">待提交</span>
          <span class="color333 font18"  v-else-if="data.status == 2">待审核</span>
          <span class="color333 font18"  v-else-if="data.status == 3">未开始</span>
          <span class="color333 font18"  v-else-if="data.status == 4">审核不通过</span>
          <span class="color333 font18"  v-else-if="data.status == 5">进行中</span>
          <span class="color333 font18"  v-else-if="data.status == 6">已过期</span>
          <span class="color333 font18"  v-else-if="data.status == 7">已关闭</span>
          <span class="color333 font18"  v-else-if="data.status == 8">已结束</span>

        </div>
      </div>
      <div class="search-button">
        <kt-button
          class="searchButton"
          :size="size"
          @click="submitReviewShow"
          v-if="statusFormat(data) == 11 || statusFormat(data) == 14"
          label="提交审核"
        ></kt-button>
        <kt-button
          class="searchButton"
          :size="size"
          @click="reviewShow"
          v-if="statusFormat(data) == 12"
          label="审核"
        ></kt-button>
<!--        <kt-button-->
<!--          class="resetButton"-->
<!--          :showImg="true"-->
<!--          :size="size"-->
<!--          @click="saveTemplateDialog"-->
<!--          label="保存模板"-->
<!--        ></kt-button>-->
      </div>
      <div class="tab-container tab-container-noPadding">
        <el-tabs v-model="active" type="border-card">
          <el-tab-pane label="促销规则" name="1">
            <div class="basicInfo ml5">基本信息：</div>
            <div class="form-group">
              <div class="color333 ml15">活动名称：</div>
              <div class="color333">{{data.promName}}</div>
            </div>
            <div class="form-group">
              <div class="color333 ml15">活动时间：</div>
              <div class="color333">{{data.startTime}} 至 {{data.endTime}}</div>
            </div>
            <div class="form-group">
              <div class="color333 ml15">活动搜索词：</div>
              <div class="color333">{{data.activitySearch}}</div>
            </div>

            <div class="form-group">
              <div class="color333 ml15">活动费用预算：</div>
              <div class="color333">{{data.activityBudget}}</div>
            </div>

            <div class="form-group">
              <div class="color333 ml15">预警比例：</div>
              <div class="color333">{{data.warningProportion}}</div>
            </div>


            <div class="basicInfo ml5">活动规则：</div>
            <div class="form-group">
              <div class="color333">每日时间段：</div>
              <div class="color333 oh">
                <div
                  v-for="(item,index) in data.responseInfoList"
                  :key="index"
                  class="mr10 f_l"
                >{{item.startTimeOfDate}} 至 {{item.endTimeOfDate}}</div>
              </div>
            </div>
            <div class="form-group">
              <div class="color333 ml15">预热时间：</div>
              <div class="color333" v-if="data.warmUpTime != undefined && data.warmUpTime != ''" >{{data.warmUpTime}}小时</div>
              <div class="color333" v-else>-</div>
            </div>
            <div class="form-group flexBox">
              <div class="color333 ml15 titleText">活动图片：</div>
              <div>
                <div class="color333 w100 mb10" v-for="(item, index) in data.imagesUrls" :key="index">
                  <el-image :src="item" style="width: 100%;height: 100%;" />
                </div>
              </div>
            </div>
            <div class=" t_l oh flex flexBox">
              <span class="color333 ml15  turnInlineBlock w80 f_l label titleText">活动描述：</span>
              <span class="color333 lh25 f_l">{{data.description}}</span>
            </div>
            <div class="basicInfo ml5">交易规则：</div>
<!--            <div class="form-group">-->
<!--              <div class="color333 ml15">是否包邮：</div>-->
<!--              <div class="color333">-->
<!--                <span v-if="data.parcelsFlag == 1">是</span>-->
<!--                <span v-if="data.parcelsFlag == 0">否</span>-->
<!--              </div>-->
<!--            </div>-->
            <div class="form-group">
              <div class="color333 ml15">超限规则：</div>
              <div class="color333">
                <template v-if="data.overLimitRule == 1">按原价购买</template>
                <template v-else-if="data.overLimitRule == 2">不可购买</template>
              </div>
            </div>
            <div class="form-group" v-if="deptType != 3">
              <div class="color333 ml15">是否分摊：</div>
              <div class="color333">
                <span v-if="data.costAllocationFlag == 1">是</span>
                <span v-if="data.costAllocationFlag == 2">否</span>
              </div>
            </div>
            <div class="basicInfo ml5">参与条件：</div>
            <div class="form-group">
              <div class="color333 ml15">新老用户：</div>
              <div class="color333">
                <span
                  v-for="(item) in (data.proUserType + '').split(',')"
                  :key="item"
                >{{getProUserType(item)}} &nbsp;</span>
              </div>
            </div>
            <div class="form-group pdl15" v-if="data.memTypes != null">
              <label class="color333 font16 ">会员类型：</label>
              <div class="color333">
                <span
                    v-for="item in (data.memTypes + '').split(
                    ','
                    )"
                    :key="item"
                    class="ng-binding ng-scope"
                >
                    <span v-if="item == 1">
                      普通会员 &nbsp;
                    </span>
                    <span v-if="item == 2">
                      we2000 &nbsp;
                    </span>
                    <span v-if="item == 3">
                      分期会员 &nbsp;
                    </span>
                </span>
              </div>
            </div>
            <div class="form-group pdl15" v-if="data.channelId != null">
              <label class="color333 font16 ">渠道入口：</label>
              <div class="color333">
                <span
                    v-for="item in (data.channelId + '').split(
                    ','
                    )"
                    :key="item"
                    class="ng-binding ng-scope"
                >
                    <span v-if="item == 1">
                        企业微信 &nbsp;
                        </span>
                        <span v-if="item == 2">
                        xxx &nbsp;
                        </span>
                        <span v-if="item == 2">
                        yyy &nbsp;
                        </span>
                </span>
              </div>
            </div>

            <div class="form-group">
              <div class="color333 ml47">备注：</div>
              <div class="color333">{{data.remark}}</div>
            </div>

          </el-tab-pane>
          <el-tab-pane label="参与商品" name="4" class="text-center">
            <div>
              <el-tabs v-model="skillTimeId" type="card" @tab-click="handleTitleClick">
                <el-tab-pane
                  :label="item.showTimeOfDate"
                  :name="item.skillTimeId"
                  v-for="(item, index) in responseInfoList"
                  :key="index"
                ></el-tab-pane>
              </el-tabs>
            </div>
            <productTemplate @findProductPage="findProductPage" ref="productTemplate"></productTemplate>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <el-dialog class="el-dialog-style" title="提交审核" :visible.sync="submitReviewVisible" v-if="submitReviewVisible">
      <p class="t_c">确认提交审核?</p>
      <span slot="footer" class="dialog-footer">
        <el-button class="cancelButton" @click="submitReviewVisible = false" :size="size">取 消</el-button>
        <el-button class="searchButton" @click="submitReview" :size="size">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog class="el-dialog-style" title="审核" :visible.sync="reviewVisible" :close-on-click-modal="false">
       <el-form :model="verifyForm" :rules="verifyFormRules" ref="verifyForm">
        <el-form-item prop="auditRemark" class="textarea">
          <el-input v-model="verifyForm.auditRemark" type="textarea" :rows="4" clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="fail" :size="size" class="cancelButton">不通过</el-button>
        <el-button type="primary" @click="success" :size="size" class="searchButton">通过</el-button>
      </span>
    </el-dialog>
    <!-- 模板弹窗 -->
    <el-dialog class="el-dialog-style" title="添加模板" :visible.sync="templateDialogFormVisible"  @close="cancel()">
      <el-form :model="templateForm" :rules="templateFormRules" ref="templateForm" label-width="130px">
        <el-form-item label="模板名称：" prop="templateName" :required="true" :show-message="false">
          <el-input v-model="templateForm.templateName" placeholder="输入模板名称" size="mini" clearable  maxlength="60"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="cancel()" size="mini" class="cancelButtton">取消</el-button>
        <el-button type="primary" @click="saveTemplate()" size="mini" class="searchButton">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import merchantTemplate from "@/views/Pages/PromotionManagement/components/PromotionMerchantTemplate";
import storeTemplate from "@/views/Pages/PromotionManagement/components/PromotionStoreTemplate";
import productTemplate from "@/views/Pages/PromotionManagement/components/PromotionProductTemplate";
import KtButton from "@/views/Core/KtButton";
import {
  promTypeConverter,
  frontPromTypeConverter,
  channelCodeConverter,
  proPlatformConverter,
  proUserTypeConverter,
  proMemberTypeConverter,
  proMemberLevelConverter,
  mutexProductLinkInfo
} from "@/market/dict/marketDict";

export default {
  components: {
    merchantTemplate,
    storeTemplate,
    productTemplate,
    KtButton
  },
  data() {
    return {
      templateDialogFormVisible: false, //模板弹窗
      templateForm: {
        templateName:""
      }, //模板model
      templateFormRules:{
        templateName:[
          { required: true, message: "请输入模板名称", trigger: "blur" },
          { required: true, message: "请输入模板名称", trigger: "change" },
          { max: 60, message: "模板名称最多60字符", trigger: "blur" },
          { max: 60, message: "模板名称最多60字符", trigger: "change" }
        ]
      },
      verifyForm: { auditRemark: "" },
      verifyFormRules:{
        auditRemark: [
          { required: true, message: "审核意见不能为空", trigger: "blur" }
        ]
      },
      promotionId: this.$route.params.promotionId,
      size: "small",
      active: "1",
      activeShop: "1",
      data: {},
      submitReviewVisible: false, //提交审核弹窗
      reviewVisible: false, //审核弹窗
      auditRemark: null, //审核意见
      skillTimeId: "",
      responseInfoList: [],
      productList: [],
      deptType: localStorage.getItem("deptType"), //当前登录用户所属组织类型
      channelList: [{ childName: "卡奥斯运营平台", id: "179" }],

      levelList: [],

    };
  },
  methods: {
    getLevelList(channelCodes){
      if(this.deptType == 0){
        //母平台
        channelCodes.forEach(item=>{
          let name = this.getChannelCodes(item);
          //获取等级
          this.data.promotionMemberGradeList.forEach(levelList=>{
            if(levelList.platformId == item){
                if(levelList.levelCodeList == null || levelList.levelCodeList.length < 1){
                  this.levelList.push({"childName":name,"childLevelList":"全部"})
                }else{
                  this.utils.request.queryMemLevelListByIds({ids:levelList.levelCodeList},res=>{
                      let levelRstList = []
                      res.data.forEach(level=>{
                        levelRstList.push(level.levelName.length >= 6 ? level.levelName.slice(0,5)+"..." : level.levelName);
                      })
                      if(item == '179'){
                        this.levelList.unshift({"childName":name,"childLevelList":levelRstList.join("|")})
                      }else{
                        this.levelList.push({"childName":name,"childLevelList":levelRstList.join("|")})
                      }
                  })
                }
            }
          })
        })
      }else{
        let user = localStorage.getItem("user");
        let userInfo = JSON.parse(user);
        if (this.data.promotionMemberGradeList == null || this.data.promotionMemberGradeList.length < 1 || this.data.promotionMemberGradeList[0].levelCodeList == null){
          this.levelList.push({"childName":userInfo.deptName,"childLevelList":"全部"})
        }else {
          this.utils.request.queryMemLevelListByIds({ids:this.data.promotionMemberGradeList[0].levelCodeList},res=>{
            let levelRstList = []
            res.data.forEach(level=>{
              levelRstList.push(level.levelName.length >= 6 ? level.levelName.slice(0,5)+"..." : level.levelName);
            })
            this.levelList.push({"childName":userInfo.deptName,"childLevelList":levelRstList.join("|")})
          })
        }
      }
    },
    getChannelCodes(code) {
      let item = this.channelList.find(function(item, index) {
        return item.id == code;
      });
      return typeof item == "undefined" ? "" : item.childName;
    },
    getProUserType(code) {
      return proUserTypeConverter(code);
    },
    saveTemplateDialog(){
      if (this.$refs['templateForm'] != undefined) {
        this.$refs['templateForm'].resetFields();
      }
      this.templateDialogFormVisible = true;
    },
    /**
     * 状态格式化
     */
    statusFormat(row) {
      if (
        row.status == 1 &&
        new Date().getTime() <= new Date(row.startTime).getTime()
      ) {
        //待提交
        return 11;
      } else if (
        row.status == 2 &&
        new Date().getTime() <= new Date(row.startTime).getTime()
      ) {
        //待审核
        return 12;
      } else if (
        row.status == 11 &&
        new Date().getTime() <= new Date(row.startTime).getTime()
      ) {
        //未开始
        return 13;
      } else if (
        row.status == 4 &&
        new Date().getTime() <= new Date(row.startTime).getTime()
      ) {
        //审核未通过
        return 14;
      } else if (
        row.status == 11 &&
        new Date().getTime() >= new Date(row.startTime).getTime() &&
        new Date().getTime() <= new Date(row.endTime).getTime()
      ) {
        //进行中
        return 15;
      } else if (
        (row.status == 1 || row.status == 2 || row.status == 4) &&
        new Date().getTime() > new Date(row.startTime).getTime()
      ) {
        //已过期
        return 16;
      } else if (
        row.status == 11 &&
        new Date().getTime() > new Date(row.endTime).getTime()
      ) {
        //已结束
        return 17;
      }
    },
    /**
     * 保存模板
     */
    saveTemplate() {
      var that = this;
      this.templateForm.promotionId = this.promotionId;
      this.$refs.templateForm.validate(valid => {
        if(valid){
          this.utils.request.skillSaveTemplate(this.templateForm, res => {
            if (res.code == "0000") {
              this.$message({ message: "保存成功", type: "success" });
              this.templateDialogFormVisible = false;
            } else {
              this.$message({ message: res.msg, type: "error" });
            }
          });
        }
      })

    },
    //保存模板弹框取消
    cancel(){
        this.templateDialogFormVisible=false;
        this.$refs.templateForm.resetFields();//关闭弹框清空表单值与校验
    },
    /**
     * 选择时间段
     */
    handleTitleClick(val) {
      //
      this.skillTimeId = val.name;
      this.findProductPage({start:1,limit:10});
      this.$refs.productTemplate.initParam(this.promotionId,this.skillTimeId);
    },
    /**
     * 商品显示
     */
    findProductPage(param) {
      let that = this;
      that.utils.request.skillQueryGoods({"promotionId": this.promotionId,"skillTimeId":this.skillTimeId,"start":param.start,"limit":param.limit}, data => {
        if (data.code=='0000' && data != null && data.data.skillGoodsTimeResponseList[0].goodsInfoList.length > 0) {
          that.$refs.productTemplate.renderProductTable({
            rows: data.data.skillGoodsTimeResponseList[0].goodsInfoList,
            total: Number(
              data.data.skillGoodsTimeResponseList[0].total
            ),
            noMutexProductLabel:data.data.skillGoodsTimeResponseList[0].skuTotal>9999? "生效商品（9999+）": "生效商品（"+data.data.skillGoodsTimeResponseList[0].skuTotal+"）",
          });
        }else{
            that.$refs.productTemplate.renderProductTable({
            rows: [],
            total: 0
          });
        }
      });

    },
    /**
     * 审核弹窗
     */
    reviewShow() {
      this.reviewVisible = true;
    },
    /**
     * 通过审核
     */
    success() {

      this.utils.request.skillCheckSkill(
        { promotionId: this.promotionId, updateStatus: 11 },
        res => {
          this.skillQueryConfig();
          this.$message({ message: "审核成功", type: "success" });
          // this.$set(this.data, "status", 3);
          this.reviewVisible = false;
        }
      );
    },
    /**
     * 不通过
     */
    fail() {
      this.$refs.verifyForm.validate((valid) => {
        if (valid) {
          this.utils.request.skillCheckSkill(
            {
              promotionId: this.promotionId,
              updateStatus: 4,
              checkRemark: this.auditRemark
            },
            res => {
              this.$message({ message: "审核成功", type: "success" });
              // this.$set(this.data, "status", 4);
              this.skillQueryConfig();
              this.reviewVisible = false;
            }
          );
        }
      });
    },
    /**
     * 提交审核
     */
    submitReview() {
      this.utils.request.skillCheckSkill(
        { promotionId: this.promotionId, updateStatus: 2 },
        res => {
          if (res.code == "0000" && res.data) {
            this.$message({ message: "提交审核成功", type: "success" });
            // this.$set(this.data, "status", 2);
            this.skillQueryConfig();
            this.submitReviewVisible = false;
          } else {
            this.$message({
              message: res.msg || "提交审核失败",
              type: "error"
            });
            this.submitReviewVisible = false;
          }
        }
      );
    },
    /**
     * 提交审核弹窗
     */
    submitReviewShow() {
      this.submitReviewVisible = true;
    },
    /**
     * 查询绑定的商家数据
     * 分页 参数 data.start data.limit
     * */
    findMerchantPage(data) {
      //TDOD
      // this.utils.request.

      //回调子组件方法 渲染表格
      //返回的数据 res.rows res.total
      let that = this;
      data.promotionId = this.promotionId;
      this.utils.request.skillQueryMerchant(data, res => {
        if (res.code == "0000") {
          if (
            res.data &&
            res.data.merchantInfoList &&
            res.data.merchantInfoList.length > 0
          ) {
            that.$refs.merchantTemplate.renderMerchantTable({
              rows: res.data.merchantInfoList,
              total: Number(res.data.total)
            });
          } else {
            that.$refs.merchantTemplate.renderMerchantTable({
              rows: [],
              total: 0
            });
          }
        } else {
          this.$message({
            message: res.msg || "获取活动商家信息失败",
            type: "error"
          });
        }
      });
    },
    /**
     * 查询绑定的店铺数据
     * 分页 参数 data.start data.limit
     * */
    findStorePage(data) {
      //TDOD
      // this.utils.request.

      //回调子组件方法 渲染表格
      //返回的数据 res.rows res.total
      let that = this;
      data.promotionId = this.promotionId;
      this.utils.request.skillQueryStore(data, res => {
        if (res.code == "0000") {
          if (
            res.data &&
            res.data.storeInfoList &&
            res.data.storeInfoList.length > 0
          ) {
            that.$refs.storeTemplate.renderStoreTable({
              rows: res.data.storeInfoList,
              total: Number(res.data.total)
            });
          } else {
            that.$refs.storeTemplate.renderStoreTable({ rows: [], total: 0 });
          }
        } else {
          this.$message({
            message: res.msg || "获取活动店铺信息失败",
            type: "error"
          });
        }
      });
    },
    getChannelName(id) {
      let item = this.channelList.find(function(item, index) {
        return item.id == id;
      });
      return typeof item == "undefined" ? "" : item.childName;
    },
    skillQueryConfig(){
      this.utils.request.skillQueryConfig({ promotionId: this.promotionId },res => {
        if(res.code=='0000'){
          this.data = res.data;
          if(res.data.channelCodes != null){
            if(res.data.channelCodes.indexOf("179") == -1){
              res.data.channelCodes.unshift("179");
            }
            this.getLevelList(res.data.channelCodes);
          }
        }
        }
      );
    },
    //保存模板弹框取消
    cancel(){
      this.templateDialogFormVisible=false;
      this.$refs.templateForm.resetFields();//关闭弹框清空表单值与校验
    }
  },
  created() {
    // if (this.deptType == 0) {
    //   this.utils.request.queryChildList({}, res => {
    //     if (res.code == "0000" && res.data && res.data.length > 0) {
    //       // channel.children = ;
    //       res.data.forEach(item => {
    //         this.channelList.push(item);
    //       });
    //     }
    //   });
    // }
  },
  mounted() {
    // this.$refs.productTemplate.initParam(this.promotionId,this.skillTimeId);
    this.skillQueryConfig();
    let this_=this;
    this.utils.request.skillQueryTimeOfDate({ promotionId: this.promotionId }, res => {
      if(res.code=='0000'){
        this_.responseInfoList = res.data.responseInfoList;
        this_.handleTitleClick({name: res.data.responseInfoList[0].skillTimeId, index: 0});
      }
      }
    );
  }
};
</script>

<style scoped lang="scss">
@import '../../../assets/css/public.scss';
.basicInfo{
  margin-left: 0px !important;
}
.ml15{
  margin-left: 15px !important;
}
.ml47{
  margin-left: 47px !important;
}
.ml5{
  margin-left: 5px !important;
}
.w80{
  width:80px
}
.pdl30{
  padding-left: 30px;
}
.lh25{
  line-height: 25px;
}
.pdl60{
  padding-left: 60px;
}
.pdl15{
  padding-left: 15px;
}
.w96{
  width: 96px !important;
}
.flex{
  display: flex;
  flex-wrap: nowrap;
  .label{
    flex-shrink:0
  }
}
.w144{
  width: 144px;
}
.oe{
  overflow: hidden;
  text-overflow:ellipsis;
  white-space: nowrap;
}
.width100{
  width: 97px;
}
.width120{
  width: 150px;
}
.mr10{
  margin-right: 10px;
}
.mb10{
  margin-bottom: 10px;
}
.ml33{
  margin-left: 33px;
}
.pdl30{
  padding-left: 30px;
}
.pdt20{
  padding-top: 20px;
}
</style>
